package com.platform.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.platform.dao.ShortUrlDao;
import com.platform.entity.ShortUrlEntity;

/**
 * 短域名对应表Service实现类
 *
 * @author LarkerJin
 * @email 277901879@qq.com
 * @date 2019-07-19 16:27:04
 */
@Service("shortUrlService")
public class ShortUrlService {
	public static Map<String,ShortUrlEntity> shortUrlMap = new HashMap<String,ShortUrlEntity>();
	
    @Autowired
    private ShortUrlDao shortUrlDao;

    /**
     * @param key = id_shortUrl
     * @return
     */
    public ShortUrlEntity getByKey(String key) {
    	ShortUrlEntity shortUrl = shortUrlMap.get(key);
    	if(shortUrl == null) {
    		String[] id_shortUrl = key.split("_");
    		Map<String,Object> params = new HashMap<String,Object>();
    		params.put("appId", id_shortUrl[0]);
    		params.put("shortUrl", id_shortUrl[1]);
    		
    		List<ShortUrlEntity> shortUrls = shortUrlDao.queryList(params);
    		if(shortUrls!= null && shortUrls.size() >0) {
    			shortUrl = shortUrls.get(0);
    			shortUrlMap.put(key, shortUrl);
    		}else {
    			return null;
    		}
    	}
        return shortUrl;
    }
    
    public ShortUrlEntity queryObject(Integer id) {
        return shortUrlDao.queryObject(id);
    }

    public List<ShortUrlEntity> queryList(Map<String, Object> map) {
        return shortUrlDao.queryList(map);
    }

    public int queryTotal(Map<String, Object> map) {
        return shortUrlDao.queryTotal(map);
    }

    public int save(ShortUrlEntity shortUrl) {
        return shortUrlDao.save(shortUrl);
    }

    public int update(ShortUrlEntity shortUrl) {
    	
    	removeFromMap(shortUrl.getId());
    	
        return shortUrlDao.update(shortUrl);
    }

    public int delete(Integer id) {
    	removeFromMap(id);
        return shortUrlDao.delete(id);
    }

    public int deleteBatch(Integer[] ids) {
    	for(Integer id:ids)
    		removeFromMap(id);
        return shortUrlDao.deleteBatch(ids);
    }
    
    private void removeFromMap(Integer id) {
    	for(Entry<String,ShortUrlEntity> shortUrl : shortUrlMap.entrySet()) {
    		if(shortUrl.getValue().getId().equals(id)) {
    			shortUrlMap.remove(shortUrl.getKey());
    			break;
    		}
    	}
    }
}
